import {createRouter, createWebHistory} from 'vue-router'

import NProgress from 'nprogress/nprogress.js'
import 'nprogress/nprogress.css'
import {useRouteStore, useUserStore} from "@/stores/index.js";
import {constantRoutes} from "./routes.js";
import setting from "@/setting.js";

const router = createRouter({
    routes: [...constantRoutes],
    history: createWebHistory()
})

const whitelist = ['/login', '/forgetPassword']

router.beforeEach(async (to, from, next) => {
    NProgress.start()
    if (whitelist.indexOf(to.path) !== -1) {
        next()
    } else {
        const userStore = useUserStore()
        const routeStore = useRouteStore()
        if (!userStore.userInfo) {
            // 1. 尝试获取用户信息
            await userStore.getUserInfo()
            if (!userStore.userInfo) {
                next({path: '/login', query: {redirect: to.path}})
            } else {
                // 2. 获取动态路由信息
                await routeStore.getRoutes(userStore.userInfo.uid)
                next({...to, replace: true})
            }
        } else {
            next()
        }
    }
})
router.afterEach((to, from) => {
    NProgress.done()
    if (to.meta.label) {
        document.title = `${setting.title}-${to.meta.label}`
    } else {
        document.title = setting.title
    }
})
export default router
